using System.Linq;
using ArticleManagementSystem.Api.Entity;
using ArticleManagementSystem.Api.Params;
using ArticleManagementSystem.Api.Repostisory;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ArticleManagementSystem.Api.Utils;
using Microsoft.Extensions.Configuration;

namespace ArticleManagementSystem.Api.Controllers
{
    //获取token权限
    // [Authorize]

    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IRepostisory<Users> _usersRepostisory;
        private readonly IRepostisory<Admin> _adminRepostisory;
        private IConfiguration _configuration;
        private TokenParameter _tokenParameter;

        public UsersController(IConfiguration configuration,IRepostisory<Users> userRepostisoy, IRepostisory<Admin> adminRepostisory)
        {
            _usersRepostisory = userRepostisoy;
            _adminRepostisory = adminRepostisory;
            _configuration = configuration;
            _tokenParameter = _configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }

        [HttpGet, Route("getusers")]
        // 查询用户列表
        public dynamic Get()
        {
            var users = _usersRepostisory.Table;
            return new
            {
                Code = 200,
                Data = users,
                Msg = "获取用户信息成功"
            };
        }

        //查询管理员
        [HttpGet, Route("getadmins")]
        public dynamic adminGet()
        {
            var users = _adminRepostisory.Table;
            var res = new
            {
                Code = 200,
                Data = users,
                Msg = "获取用户信息成功"
            };
            return JsonHelper.Serialize(res);
        }


        // 注册
        [AllowAnonymous]
        [HttpPost, Route("registry")]
        public dynamic Post(CreateUsers newUser)
        {
            var Username = newUser.Username.Trim();
            var Password = newUser.Password.Trim();
            var RePassword = newUser.RePassword.Trim();


            if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
            {

                if (!Password.Equals(RePassword))
                {
                    return new
                    {
                        code = 200,
                        data = "",
                        msg = "两次输入的密码不一致"
                    };
                }

                var users = _usersRepostisory.Table;
                var isHaveUser = users.Where(x => x.Username.Equals(Username)).ToList();

                if (isHaveUser.Count() == 0)
                {
                    var addUser = new Users
                    {
                        Password = Password,
                        Username = Username
                    };

                    _usersRepostisory.Insert(addUser);

                    return new
                    {
                        code = 200,
                        data = addUser,
                        msg = "用户创建成功"
                    };
                }
                else
                {
                    //该用户已存在
                    return new
                    {
                        code = 104,
                        data = "",
                        msg = "该用户已存在"
                    };
                }

            }
            else
            {
                //用户名密码不能为空
                return new
                {
                    code = 104,
                    data = "",
                    msg = "用户名密码不能为空"
                };
            }
        }


        // 登录
        // [AllowAnonymous]
        // [HttpPost, Route("login")]
        // public dynamic post(Login login)
        // {
        //     var Username = login.Username.Trim();
        //     var Password = login.Password.Trim();

        //     if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
        //     {
        //         var user = _usersRepostisory.Table;
        //         var u = user.Where(x => x.Username.Equals(Username) && x.Password.Equals(Password));

        //         if (u.Count() != 0)
        //         {
        //             if (u.FirstOrDefault().IsActived == false)
        //             {
        //                 return new
        //                 {
        //                     code = 200,
        //                     data = u,
        //                     msg = "该用户已被注销"
        //                 };
        //             }
        //             return new
        //             {
        //                 code = 200,
        //                 data = u,
        //                 msg = "登陆成功"
        //             };
        //         }
        //         else
        //         {
        //             return new
        //             {
        //                 code = 104,
        //                 data = u,
        //                 msg = "用户名密码错误"
        //             };
        //         }
        //     }
        //     else
        //     {
        //         return new
        //         {
        //             code = 104,
        //             msg = "请输入用户名密码"
        //         };
        //     }
        // }


        //获取用户token登录
        [AllowAnonymous]
        [HttpPost, Route("userstoken")]
        public dynamic GetUsersToken(Login login)
        {
            var Username = login.Username.Trim();
            var Password = login.Password.Trim();
            var user = _usersRepostisory.Table.Where(x => x.Username == Username && x.Password == Password).FirstOrDefault();

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不正确 请确认充实"
                };
            }
            var userid = user.Id;
            var userName = user.Username;
            var token = TokenHelper.GenUserToken(_tokenParameter, user.Username);

            var refreshToken = "123456789";

            return new
            {
                Code = 1000,
                Data = new { Token = token, refreshToken = refreshToken ,UserId =  userid,Username = userName},
                Msg = "登录成功"
            };

            // if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
            // {
            //     var user = _usersRepostisory.Table;
            //     var u = user.Where(x => x.Username.Equals(Username) && x.Password.Equals(Password));

            //     if (u.Count() != 0)
            //     {
            //         if (u.FirstOrDefault().IsActived == false)
            //         {
            //             return new
            //             {
            //                 code = 200,
            //                 data = u,
            //                 msg = "该用户已被注销"
            //             };
            //         }
            //         var token = TokenHelper.GenUserToken(_tokenParameter, u.Username);

            //         var refreshToken = "123456789";
            //         return new
            //         {
            //             code = 200,
            //             data = u,
            //             msg = "登陆成功"
            //         };
            //     }
            //     else
            //     {
            //         return new
            //         {
            //             code = 104,
            //             data = u,
            //             msg = "用户名密码错误"
            //         };
            //     }
            // }
            // else
            // {
            //     return new
            //     {
            //         code = 104,
            //         msg = "请输入用户名密码"
            //     };
            // }
        }


        //刷新重新获取token,refreshToken
        [AllowAnonymous]
        [HttpPost, Route("userRefreshToken")]
        public dynamic UserRefreshTokenPost(RefreshTokenDTO refresh)
        {
            var user = TokenHelper.ValidateToken(_tokenParameter, refresh);

            if (string.IsNullOrEmpty(user))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "userRefreshToken验证失败"
                };
            }
            var token = TokenHelper.GenUserToken(_tokenParameter, user);

            var refreshToken = "123456789";

            return new
            {
                Code = 200,
                Data = new{ Token = token, refreshToken = refreshToken },
                Msg = "刷新重新获取token,refreshToken成功"
            };
        }


        //管理员登录
        [AllowAnonymous]
        [HttpPost, Route("adminLogin")]
        public dynamic adminpost(AdminUsers admin)
        {
            var AdminUsername = admin.AdminUsername.Trim();
            var AdminPassword = admin.AdminPassword.Trim();

            if (!string.IsNullOrEmpty(AdminUsername) && !string.IsNullOrEmpty(AdminPassword))
            {
                var user = _adminRepostisory.Table;
                var u = user.Where(x => x.AdminUsername.Equals(AdminUsername) && x.AdminPassword.Equals(AdminPassword));

                if (u.Count() != 0)
                {
                    if (u.FirstOrDefault().IsActived == false)
                    {
                        return new
                        {
                            code = 104,
                            data = u,
                            msg = "该用户已被注销"
                        };
                    }
                    return new
                    {
                        code = 200,
                        data = u,
                        msg = "登陆成功"
                    };
                }
                else
                {
                    return new
                    {
                        code = 104,
                        data = u,
                        msg = "用户名密码错误"
                    };
                }
            }
            else
            {
                return new
                {
                    code = 104,
                    msg = "请输入用户名密码"
                };
            }
        }


        //分配管理员
        [AllowAnonymous]
        [HttpPost, Route("administrators")]
        public dynamic Post(CreateAdministrators administrators)
        {
            // var res = new Admin
            // {
            //     AdminUsername = "admin",
            //     AdminPassword = "999"
            // };
            // _adminRepostisory.Insert(res);
            // return res;

            var username = administrators.Username.Trim();
            var password = administrators.Password.Trim();

            var user = _adminRepostisory.Table;
            // var v = user.Where(x => x.AdminPassword.Equals(password)).FirstOrDefault();



            if (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(username))
            {

                var addadministrators = new Admin
                {
                    AdminUsername = username,
                    AdminPassword = password
                };
                _adminRepostisory.Insert(addadministrators);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = addadministrators,
                    Msg = "创建管理员成功"
                });

            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "创建管理员错误"
                };
            }
        }

        //修改用户密码
        [HttpPut, Route("{id}/userpassword")]
        public dynamic Put(int id, ChangeUsers changeUsers)
        {
            var username = changeUsers.Username.Trim();
            var password = changeUsers.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = "104",
                    Data = "",
                    Msg = "用户名或密码不能为空"
                };
            }
            else
            {
                var users = _usersRepostisory.GetById(id);
                if (users == null)
                {
                    return new
                    {
                        Code = "104",
                        Data = "",
                        Msg = "需要修改的用户不存在"
                    };
                }
                users.Username = changeUsers.Username;
                users.Password = changeUsers.Password;

                _usersRepostisory.Updated(users);
                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = users,
                    Msg = "更新成功"
                });
            }
        }



        //admin修改密码
        [HttpPut, Route("{id}/adminpassword")]
        public dynamic adminPut(int id, ChangeAdmin changeAdmin)
        {
            var username = changeAdmin.adminUsername.Trim();
            var password = changeAdmin.adminPassword.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return new
                {
                    Code = "104",
                    Data = "",
                    Msg = "用户名或密码不能为空"
                };
            }
            else
            {
                var users = _adminRepostisory.GetById(id);
                if (users == null)
                {
                    return new
                    {
                        Code = "104",
                        Data = "",
                        Msg = "需要修改的用户不存在"
                    };
                }
                users.AdminUsername = changeAdmin.adminUsername;
                users.AdminPassword = changeAdmin.adminPassword;

                _adminRepostisory.Updated(users);

                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = users,
                    Msg = "更新管理员成功"
                });
            }
        }

        //删除admin
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            _adminRepostisory.Deleted(id);
            return new
            {
                Code = 200,
                Data = "",
                Msg = "删除管理员成功"
            };
        }



        //封号(冻结用户)
        // [HttpPut("{id}")]
        // public dynamic Put(int id, DeleteUsers deleteUsers)
        // {
        //     var username = deleteUsers.Username.Trim();
        //     var password = deleteUsers.Password.Trim();
        //     if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
        //     {
        //         return new
        //         {
        //             Code = 104,
        //             Data = "",
        //             Msg = "用户名或密码不能为空"
        //         };
        //     }

        //     var user = _usersRepostisory.GetById(id);

        //     if (user == null)
        //     {
        //         return new
        //         {
        //             Code = 104,
        //             Data = "",
        //             Msg = "要注销的用户不存在，请确认后重试"
        //         };
        //     };
        //     user.IsActived = false;

        //     _usersRepostisory.Updated(user);


        //     return new
        //     {
        //         StatusCode = 200,
        //         Data = user,
        //         Msg = "封号十年！！！"
        //     };
        // }
    }
}